let student_list = [],
    student_list_next = [],
    student_list_last = [],
    student_name = [],
    student_id = [],
    stutent_inforamtion = [],
    student_course_inforamation = {}
import { getWeekDateNew } from '/js/util.js'
import { classHistoryOpenListener } from './fileClassListener.js'
import { dialogOrderListener, dialogPriceListener } from './listener.js'


import { unfoldOpenListener, comingListener, passByListener, studentUp, fileClassListener } from './mainPageListener.js'

// current page component
let currentOpenClassName = "component-wrap";


// teacher class main page listener
let MyClassMainListener = () => {
    // lookup student by teacher
    unfoldOpenListener();
    comingListener();
    passByListener();
    fileClassListener(currentOpenClassName);
    classHistoryOpenListener();
    changePriceListener();
    cancelOrderBtnListener();
    changeOrderBtnListener();
};

// lookup student
let lookUpStudentList = async () => {
    let res = await ajax('teacher_teaching_record', {
        state: 1
    }, 'post')
    if (res?.data.length) {
        student_name = []
        student_id = []
        res.data.forEach(item => {
            if (!student_name.includes(item.name)) {
                student_name.push(item.name)
            }
            if (!student_id.includes(item.studentid)) {
                student_id.push(item.studentid)
            }
            item.time = new Date(item.lecturet)
        })
        let student_list1 = res.data
        if (student_list1.length) {
            student_list_next = student_list1.filter(item => {
                return item.time > new Date().getTime()
            })
            student_list_last = student_list1.filter(item => {
                return item.time < new Date().getTime()
            })
            student_list_next.forEach(item => {
                if (student_course_inforamation[item.studentid]?.student_list_next) {
                    student_course_inforamation[item.studentid]['student_list_next'].push(item)
                } else {
                    student_course_inforamation[item.studentid] = {
                        'student_list_next': [item]
                    }
                }
            })
            student_list_last.forEach(item => {
                if (student_course_inforamation[item.studentid]?.student_list_last) {
                    student_course_inforamation[item.studentid]['student_list_last'].push(item)
                } else {
                    if (student_course_inforamation[item.studentid]) {
                        student_course_inforamation[item.studentid].student_list_last = [item]
                    } else {
                        student_course_inforamation[item.studentid] = {
                            'student_list_last': [item]
                        }
                    }

                }
            })
            console.log(student_course_inforamation)
            return true
        }
    } else {
        return false
    }
}

// teacher lookup recently course information
let teacherLooupRecentlyCourse = async () => {
    let res = await ajax('teacher_query_j', {
        cuyear: new Date().getFullYear(),
        cumonth: new Date().getMonth() + 1,
        coursetime: new Date().getDay() === 0 ? 7 : new Date().getDay(),
        userid: JSON.parse(localStorage.getItem('user')).user_id,
        cuday: new Date().getDate()
    }, 'post')
    if (res.data.length) {
        res.data = res.data.filter(item => {
            let time = new Date(`${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${new Date().getHours()}:00:00`).getTime()
            let time2 = new Date(`${item.cuyear}-${item.cumonth}-${item.cuday} ${item.timequantum}`).getTime()
            let time3 = time2 + 1000 * 60 * 60
            if (time2 >= time && item.state === 0) {
                return true
            } else {
                return false
            }
        })
        if (res.data.length) {
            $('.next-course-title')[0].innerText = `: ${res.data[0].cuyear}年${res.data[0].cumonth}月${res.data[0].cuday}日，${getWeekDateNew(res.data[0].coursetime)}${res.data[0].timequantum}`
            $('.next-course-img')[0].src = res.data[0].teacherimg
        }

    }
    return res.data
}

// main page init
let createTeacherClassWrap = async () => {
    return new Promise(async (resolve) => {
        student_list = []
        student_list_next = []
        student_list_last = []
        student_name = []
        student_id = []
        stutent_inforamtion = []
        student_course_inforamation = {}
        let result = await lookUpStudentList()
        let componentWrap = document.createElement("div");
        componentWrap.className = "component-wrap";
        if (result) {
            componentWrap.appendChild(createTeacherClassWrapTop());
            componentWrap.appendChild(createTeacherClassWrapBottom());
            $(".body")[0].appendChild(componentWrap);
            student_id.forEach((item, index) => {
                let length = (student_course_inforamation[item]?.student_list_next?.length || 0) + (student_course_inforamation[item]?.student_list_last?.length || 0)
                let list = student_course_inforamation[item]?.student_list_next ? student_course_inforamation[item]?.student_list_next[0] : student_course_inforamation[item]?.student_list_last[0]
                createStudentList(list, length, index);
                if (student_course_inforamation[item]?.student_list_next?.length) {
                    createStudentListNext(student_course_inforamation[item].student_list_next, index)
                }
                if (student_course_inforamation[item]?.student_list_last?.length) {
                    createStudentListBefore(student_course_inforamation[item].student_list_last, index)
                }


            })

            studentUp();
            MyClassMainListener();
            stutent_inforamtion = await teacherLooupRecentlyCourse()
            if (Object.keys(stutent_inforamtion).length) {
                enterCourse()
            }
        } else {
            componentWrap.innerHTML = `
            <div class='animated fadeIn no-message'>暂时没有课程记录...</div>
        `
            $(".body")[0].appendChild(componentWrap);
        }
        setTimeout(() => {
            $('.component-wrap')[0].style.opacity = 1
            resolve('ok')
        })
    })

};

// main page top
let createTeacherClassWrapTop = () => {
    let top = document.createElement("div");
    top.className = "component-class-top animated fadeInDown";
    top.innerHTML = `
        <div style='display:flex;align-items:center'>
            <svg style="width: 38px;height:38px;" class='ml-28' aria-hidden="true">
                <use xlink:href="#icon-shipin"></use>
            </svg>
            <span style='margin-left:18px;color:#878787'>下一课</span>
            <span class='next-course-title'>:</span>
            <img class='next-course-img' src='../../../static/anquan.png' width='29' height='29' style='border-radius:50%;margin-left:11px'/>
        </div>
        <div class='component-class-top-enter'>进入课堂</div>
    `;
    return top;
};

// create student list (main page)
let createStudentList = (list, length, index) => {
    let frag = document.createDocumentFragment();
    let componentClassBottomList3 = document.createElement("div");
    componentClassBottomList3.className = "component-class-bottom-list3";
    componentClassBottomList3.innerHTML = `
        <div class='component-class-bottom-list3-one'>
            <i class='iconfont icon-xiangxia student-xiangxia' data-index=${index} style='color:#858585;margin-right:0;transform:rotate(360deg);transition:.4s'></i>
            <img style='margin-left:8px' src='${list.teacherimg}' width='28' height='28'/>
            <span style='margin-left:15px'>${list.name + '（学生）'}</span>
        </div>
        <div class='component-class-bottom-list3-two'>
            ${length}节课
        </div>
        <div class='component-class-bottom-list3-three'>
            $${list.price}
        </div>
        <div class='component-class-bottom-list3-four'> 
            <div style='color:#5686E9;display:flex;align-items:center'>
                <i class='iconfont icon-yueke'></i>
                <span class='class-message' style='margin-left:4px;cursor:pointer'>约课</span>
            </div>
            <div style='color:#5686E9;display:flex;align-items:center'>
                <i class='iconfont icon-xinxi'></i>
                <span class='class-message' style='margin-left:4px;cursor:pointer'>信息</span>
            </div>
            <div style='color:#E9B356;display:flex;align-items:center'>
                <i class='iconfont icon-jilu1'></i>
                <span data-userid='${list.studentid}' style='margin-left:4px;cursor:pointer' class='openClassHistory'>课程记录</span>
            </div>
            <div class='unfold'>
                <span data-index=${index} class='unfold-open-click' style='user-select:none'>...</span>
                <div class='unfold-bubble unfold-bubble${index}' style='display:none'>
                    <div class='unfold-bubble-list'>
                        <i class='iconfont icon-genggai'></i>
                        <span class='unfold-bubble-list-text' style='color:white'>更改（学生）名称</span>
                    </div>
                    <div class='unfold-bubble-list'>
                        <i class='iconfont icon-a-wenjianjiawenjian'></i>
                        <span class='unfold-bubble-list-text' style='color:white'>归档</span>
                    </div>
                    <div class='unfold-bubble-list'>
                        <i class='iconfont icon-xiugaijiage'></i>
                        <span class='unfold-bubble-list-text' style='color:white'>修改价格</span>
                    </div>
                </div>
            </div>
        </div>
    `;
    let componentClassBottomStudentDetail = document.createElement('div')
    componentClassBottomStudentDetail.className = `component-class-bottom-student-detail${index}`
    componentClassBottomStudentDetail.innerHTML = `
        <div class='component-class-bottom-list4'>
            <div style='margin-left:28px'>日期</div>
            <div>状态</div>
            <div>时长</div>
            <div>收入</div>
            <div>变更</div>
        </div>
        <div style='height: 22px;background: #FFFFFF;width:100%;display: flex;align-items: center;'>
            <i data-index=${index} class='iconfont icon-xiangxia coming' style='margin-left:13px;margin-right:4px;font-size:8px;transform:rotate(360deg);transition:.4s'></i>
            <span style='font-size:8px'>未来</span>
        </div>
        <div class='component-class-bottom-list-next-wrap${index}'>
            
        </div>
        <div style='height: 22px;background: #FFFFFF;width:100%;display: flex;align-items: center;'>
            <i data-index=${index} class='iconfont icon-xiangxia pass-by' style='margin-left:13px;margin-right:4px;font-size:8px;transform:rotate(360deg);transition:.4s'></i>
            <span style='font-size:8px'>过去</span>
        </div>
        <div class='component-class-bottom-list-before-wrap${index}'>

        </div>  
    `
    frag.appendChild(componentClassBottomList3)
    frag.appendChild(componentClassBottomStudentDetail)
    $('.component-class-bottom')[0].appendChild(frag)

    $('.class-message')[1].addEventListener('click', () => {
        location.reload()
    })
};

// create student list next 
let createStudentListNext = (list, index) => {
    console.log(list, 'awedaw')
    let wrap = document.createDocumentFragment()
    list.forEach(item => {
        let next_wrap = document.createElement('div')
        next_wrap.className = `component-class-bottom-list-next component-class-bottom-list-next${index}`
        next_wrap.dataset.curriculumid = item.curriculumid
        let weekday = {
            1: '星期一',
            2: '星期二',
            3: '星期三',
            4: '星期四',
            5: '星期五',
            6: '星期六',
            7: '星期日',
        }
        next_wrap.innerHTML = `
            <div style='margin-left:28px'>每周</div>
            <div>${weekday[item.coursetime]}${item.timequantum}</div>
            <div>50分钟</div>
            <div>-----</div>
            <div style='display:block;'>
                <div class='component-class-bottom-cancel'>
                    <i class='iconfont icon-biangeng' style='font-size:11px;margin-right:4px'></i>
                    <span class='change-order-open'>变更</span>
                </div>
                <div class='component-class-bottom-cancel'>
                    <i class='iconfont icon-chahao' style='font-size:11px;margin-right:4px'></i>
                    <span class='cancel-order-open'>取消</span>
                </div>
            </div>
        `
        wrap.appendChild(next_wrap)
    })
    $(`.component-class-bottom-list-next-wrap${index}`)[0].appendChild(wrap)
}

// create student list before
let createStudentListBefore = (list, index) => {
    let wrap = document.createDocumentFragment()
    list.forEach(item => {
        let before_wrap = document.createElement('div')
        before_wrap.className = `component-class-bottom-list-before component-class-bottom-list-before${index}`
        let weekday = {
            1: '星期一',
            2: '星期二',
            3: '星期三',
            4: '星期四',
            5: '星期五',
            6: '星期六',
            7: '星期日',
        }
        before_wrap.innerHTML = `
            <div style='margin-left:28px'>${item.lecturet.split(' ')[0]}日${weekday[item.coursetime]}</div>
            <div>${weekday[item.coursetime]}${item.timequantum}</div>
            <div>50分钟</div>
            <div>$${item.price}</div>
            <div></div>
        `
        wrap.appendChild(before_wrap)
    })
    $(`.component-class-bottom-list-before-wrap${index}`)[0].appendChild(wrap)
}

// main page bottom
let createTeacherClassWrapBottom = () => {
    
    let bottom = document.createElement("div");
    bottom.className = "component-class-bottom animated fadeInDown";
    bottom.innerHTML = `
        <div class='component-class-bottom-list1'>
            <span class='ml-28' style='flex:1'></span>
            <div class='file-class'>归档的课程</div>
        </div>
        <div class='component-class-bottom-list2'>
            <div>（学生）</div>
            <div>已支付</div>
            <div>每节课的价格</div>
            <div style='flex-direction: row-reverse;margin-right: 24px;'>安排</div>
        </div>
    `;
    return bottom;
};


// create price dialog
let createChangeClassPriceDialog = () => {
    let classPriceDialog = document.createElement("div");
    classPriceDialog.className = "class-price-dialog";
    classPriceDialog.innerHTML = `
        <div class='class-price-dialog-top'>
            <span style='margin-left:23px;font-weight: bold;'>更改课程单价</span>
            <i class='iconfont icon-chahao chahao' style='font-size:11px;color:#B5B5B5;margin-right:22px'></i>
        </div>
        <div style='padding-left:23px;color:#838383'>
            <div style='margin-top:9px'>更改之前，请跟（学生）确认:</div>
            <div style='margin-top:10px'>·同意价格变更</div>
            <div style='margin-top:8px'>·没有已经约好的课程，没有未确认的课程</div>
            <div style='margin-top:10px'>如果（学生）还有未使用的课程，将根据新价格重新计算</div>
            <div style='margin-top:9px;color:#3C3C3C;font-weight:bold'>决定之后，我们将和您的（学生）确认新价格</div>
            <div class='class-price-dialog-every'>
                <div>每节课:</div>
                <input />
                $
            </div>
            <div class='class-price-dialog-btn'>
                <div class='set'>set new price</div>
                <span>or</span>
                <div style='margin-left:13px' class='chahao'>cancel</div>
            </div>
        </div>
    `;
    $(".body")[0].appendChild(classPriceDialog);

    dialogPriceListener();
};


// main page listener
let changePriceListener = () => {
    $(".unfold-bubble-list-text")[2].addEventListener("click", () => {
        $("#mask").show();
        $("#mask")[0].style.zIndex = 20;
        createChangeClassPriceDialog();
    });
};

// cancel order dialog
let cancelOrderDialog = (curriculumid,el) => {
    let cancelOrder = document.createElement("div");
    cancelOrder.className = "cancel-order-dialog";
    cancelOrder.innerHTML = `
        <div class='class-price-dialog-top'>
            <span style='margin-left:23px;font-weight: bold;'>取消预约</span>
            <svg style="width: 36px;height:36px;margin-right: 40px;margin-bottom:4px;margin-top:4px" class='' aria-hidden="true">
                <use xlink:href="#icon-jinggao"></use>
            </svg>
            <i class='iconfont icon-chahao order-chahao'></i>
        </div>
        <div style='margin-left:23px;margin-top:12px;color:#777777;margin-bottom:25px'>
            尽量不要取消，取消会直接影响您的排名和出勤率。
        </div>
        <div style='margin-left:23px;margin-top:12px;color:#777777;margin-bottom:25px'>
            提前尝试和（学生）变更到其他时间。
        </div>
        <div style='margin-left:23px;margin-top:12px;color:#777777;margin-bottom:25px'>
            不要拖到（学生）投诉。
        </div>
        <div class='cancel-order-btn'>
            <div class='change-order'>变更预约</div>
            <div class='cancel-order'>取消预约</div>
        </div>
    `;

    $(".body")[0].appendChild(cancelOrder);
    dialogOrderListener(curriculumid,el);
};

// cancel order dialog
let changeOrderDialog = (curriculumid,el) => {
    let cancelOrder = document.createElement("div");
    cancelOrder.className = "cancel-order-dialog";
    cancelOrder.innerHTML = `
        <div class='class-price-dialog-top'>
            <span style='margin-left:23px;font-weight: bold;'>变更预约</span>
            <svg style="width: 36px;height:36px;margin-right: 40px;margin-bottom:4px;margin-top:4px" class='' aria-hidden="true">
                <use xlink:href="#icon-biangeng"></use>
            </svg>
            <i class='iconfont icon-chahao order-chahao'></i>
        </div>
        <div style='margin-left:23px;margin-top:12px;color:#777777;margin-bottom:25px'>
            尽量提前和学生沟通，取得同意后变更。不要拖到学生投诉。
        </div>
        <div style='margin-left:23px;margin-top:12px;color:#777777;margin-bottom:25px'>
            变更不会影响您的排名，但会影响您的出勤率。
        </div>
        <div style='margin-left:23px;margin-top:12px;color:#777777;margin-bottom:25px'>
            变更后一定反映到日历里，特别是每周的定期课。否则，极有可能会发生重复预约。
        </div>
        <div class='cancel-order-btn'>
            <div class='change-order'>确定</div>
            <div class='cancel-order'>取消</div>
        </div>
    `;

    $(".body")[0].appendChild(cancelOrder);
    dialogOrderListener(curriculumid,el);
};


// enter in course
let enterCourse = () => {
    $('.component-class-top-enter')[0].addEventListener('click', () => {
        let time = new Date(`${stutent_inforamtion[0].cuyear}-${stutent_inforamtion[0].cumonth}-${stutent_inforamtion[0].cuday} ${stutent_inforamtion[0].timequantum}`).getTime()
        let time1 = time + 1000 * 60 * 60
        if (new Date().getTime() > time && new Date().getTime() < time1) {
            let userid = stutent_inforamtion[0].studentid
            let curriculumid = stutent_inforamtion[0].curriculumid
            let location = `/views/attendClass/teacher/classHistory.html?teacherid=${userid}&curriculumid=${curriculumid}&state=1`
            window.location.href = location
        } else {
            Dreamer.error('未到上课时间!')
        }

    })
}

// calcel order dialog listener
let cancelOrderBtnListener = () => {
    $(".cancel-order-open").each(function (index) {
        $(this).on("click", (e) => {
            $("#mask").show();
            $("#mask")[0].style.zIndex = 20;
            cancelOrderDialog($(e.target).parents('div.component-class-bottom-list-next')[0].dataset.curriculumid,$(e.target).parents('div.component-class-bottom-list-next')[0]);
        });
    });
};


// change order dialog listener
let changeOrderBtnListener = () => {
    $(".change-order-open").each(function (index) {
        $(this).on("click", (e) => {
            $("#mask").show();
            $("#mask")[0].style.zIndex = 20;
            changeOrderDialog($(e.target).parents('div.component-class-bottom-list-next')[0].dataset.curriculumid,$(e.target).parents('div.component-class-bottom-list-next')[0]);
        });
    });
}


export {
    createTeacherClassWrap
};